##    PSF LICENSE AGREEMENT FOR PYTHON 2.4
##    ------------------------------------
##
##    1. This LICENSE AGREEMENT is between the Python Software Foundation
##    ("PSF"), and the Individual or Organization ("Licensee") accessing and
##    otherwise using Python 2.4 software in source or binary form and its
##    associated documentation.
##
##    2. Subject to the terms and conditions of this License Agreement, PSF
##    hereby grants Licensee a nonexclusive, royalty-free, world-wide
##    license to reproduce, analyze, test, perform and/or display publicly,
##    prepare derivative works, distribute, and otherwise use Python 2.4
##    alone or in any derivative version, provided, however, that PSF's
##    License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
##    2001, 2002, 2003, 2004 Python Software Foundation; All Rights Reserved"
##    are retained in Python 2.4 alone or in any derivative version prepared
##    by Licensee.
##
##    3. In the event Licensee prepares a derivative work that is based on
##    or incorporates Python 2.4 or any part thereof, and wants to make
##    the derivative work available to others as provided herein, then
##    Licensee hereby agrees to include in any such work a brief summary of
##    the changes made to Python 2.4.
##
##    4. PSF is making Python 2.4 available to Licensee on an "AS IS"
##    basis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
##    IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
##    DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
##    FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.4 WILL NOT
##    INFRINGE ANY THIRD PARTY RIGHTS.
##
##    5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
##    2.4 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
##    A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.4,
##    OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
##
##    6. This License Agreement will automatically terminate upon a material
##    breach of its terms and conditions.
##
##    7. Nothing in this License Agreement shall be deemed to create any
##    relationship of agency, partnership, or joint venture between PSF and
##    Licensee.  This License Agreement does not grant permission to use PSF
##    trademarks or trade name in a trademark sense to endorse or promote
##    products or services of Licensee, or any third party.
##
##    8. By copying, installing or otherwise using Python 2.4, Licensee
##    agrees to be bound by the terms and conditions of this License
##    Agreement.
#--
#   Television Episode Renamer
#   - External RC2: April 29th 2008
#       - Fixed issue on the precedence of command line options > preferences file > preference in the script, should work
#       - Fixed issue on where to find resource files
#       - Removed checking for non-ascii characters due to error running from command line, need to flesh out
#   - External RC1: April 28th 2008
#       - Fully embrace the config file lifestyle. All sources exist as an external .source
#       - Redid the default option system completely
#   - Internal Milestone 6: April 16th, 2008 - April 19th, 2008
#       - Handles double episodes, based on splitChar
#       - Much better control flow, safer overwrites
#       - Correct and better command line options
#       - can use the tv.com all episodes summary page to rename a full run
#       - tv.com txt file support
#   - Internal Milestone 5: April 10th, 2008 - April 16th, 2008
#       - tv.com support, website (/), cache (/)
#       - splitting up a complete series folder, when numbered in air order /
#       - support .html versions as file /
#   - Internal Milestone 4: April 8th, 2008 to April 10th, 2008
#       - optionize more assumptions /
#       - handle showname/Season # /
#       - more judicious printing - eg: handle folder as a batch? /
#       - seperate verbose and debug print /
#       - decide "normal" printouts /
#       - reduce O(n) where obvious /
#       - interactive/batch mode /
#   - Internal Milestone 3: April 6th, 2008 - April 8th, 2008
#       - option to walk directory structure from given location
#       - optparse add and support
#   - Internal Milestone 2: April 5th, 2008 to April 6th, 2008
#       - search an epguides.txt file and html page and fill out ep title
#   - Internal Milestone 1: April 2nd, 2008 to April 5th, 2008
#       - construct new name based on Template
#       - correctly interact with rename_list, make batch/sh/etc and better
#   - Initial Milestone: April 2nd, 2008
#       - Find URL from epguides.com
#       - filenames to rename_list.csv

#   - Eventual Goals
#       - Nice to Have
#           - create html page with each file's link to recap
#               + page has link to dvd/show site image, saved to dir as folder.jpg
#           - saving source site to plain text
#           - add new sources
#           - pull the recap from epguides/other guides (twop) to dir
#           - interaction with TED/miro/other open source players
#       - Non-standard numbering
#           - clip shows, miniseries, pilots, unaired pilots
#           - British conventions
#               + Series "names" as in Blackadder Goes Fourth
#       - Interaction
#           - create a simple breakpoint function for debug
#       - Files/Folders organization issues
#           - get/confirm show name from the filename
#           - for complete series in one folder, split it into seperate folders
#           - fully handle folder schemes that aren't too weird
#           - Option to move files into new folders
#
#   Rob Dennis  - Lurchington Q. Delacroix ESQ. and man about town
#
#   This script is inspired and is thanks to: 
#   -   Rob Meerman's tvrenamer perl script
#           http://www.robmeerman.co.uk/coding/file_renamer
#   -   Softpointer's Tag&Rename
#           http://www.softpointer.com/tr
#   
#--

import os,re,glob,time,sys,string,shutil,urllib2,ConfigParser
from string import Template
from optparse import OptionParser

unparsedFiles = []
unfoundWebsites = []
collisionFiles = []

osRenameCommand = "mv"
undoBatchName = "undoBatch.sh"
nameBatchName = "nameBatch.sh"
batchHeaderString = r"#!/bin/bash"

parser = OptionParser(version="%prog - External RC2 - April 29th, 2008")

parser.add_option("-u","--makeUndoBatchFile",dest="undoBatchFlag",action="store_true",
                  help="enable creation of naming batch file [default: %default]")

parser.add_option("-U","--noMakeUndoBatchFile",dest="undoBatchFlag",action="store_false",
                  help="disable creation of naming batch file")

parser.add_option("-n","--makeNamingBatchFile",dest="nameBatchFlag",action="store_true",
                  help="enable creation of undo batch file [default: %default]")

parser.add_option("-N","--noMakeNamingBatchFile",dest="nameBatchFlag",action="store_false",
                  help="disable creation of undo batch file")

parser.add_option("-w","--writeCacheToFile",dest="writeCacheToFileFlag",action="store_true",
                  help="writes webpage cache to text file in dir [default: %default]")

parser.add_option("-W","--noWriteCacheToFile",dest="writeCacheToFileFlag",action="store_false",
                  help="does not write webpage cache to text file in dir")

parser.add_option("--quashBatchEntries",dest="quashBatchEntriesFlag",action="store_true",
                  help="always overwrite batch file [default: %default]")

parser.add_option("--noQuashBatchEntries",dest="quashBatchEntriesFlag",action="store_false",
                  help="only add new entries to batch file")

parser.add_option("-p","--pretend",dest="pretendFlag",action="store_true",
                  help="do not make any changes [default: %default]")

parser.add_option("-c","--confirm",dest="pretendFlag",action="store_true",
                  help="make changes where desired")

parser.add_option("-m","--guessMultipart",dest="guessMultipartFlag",action="store_true",
                  help="will not read Part 1 in title as episode number 1 [default: %default]")

parser.add_option("-M","--noGuessMultipart",dest="guessMultipartFlag",action="store_false",
                  help="will not try to guess multi-part episodes from filename")

parser.add_option("--handleFullRun",dest="handleFullRunFlag",action="store_true",
                  help="for episodes numbered with the overall show order [default: %default]")

parser.add_option("--noHandleFullRun",dest="handleFullRunFlag",action="store_false",
                  help="no special handling for overall show order")

parser.add_option("-s","--splitFullRun",dest="splitFullRunFlag",action="store_true",
                  help="split full run into season and episode [default: %default]")

parser.add_option("-S","--noSplitFullRun",dest="splitFullRunFlag",action="store_false",
                  help="don't split full run into season and episode")

parser.add_option("--guessShowNameFlag",dest="guessShowFromNameFlag",action="store_true",
                  help="deals with showname in fileName (unwieldy)")

parser.add_option("--noGuessShowNameFlag",dest="guessShowFromNameFlag",action="store_false",
                  help="does not attenmpt to deal with shawname in filename")

parser.add_option("-a","--assumeGroupedNum",dest="assumeGroupedNumFlag",action="store_true",
                  help="treats fields like 1005 as both season and episode number [default: %default]")

parser.add_option("-A","--noAssumeGroupedNum",dest="assumeGroupedNumFlag",action="store_false",
                  help="treats fields like 1005 as one number")

parser.add_option("-g","--groupNumSplit",dest="groupNumSplit",metavar="NUM",type="int",
                  help="when handling group numbers, split after NUM places [default: %default]")

parser.add_option("-G","--episodePadding",dest="episodePadding",metavar="NUM",type="int",
                  help="pads episode number to NUM places [default: %default]")

parser.add_option("--seasonPadding",dest="seasonPadding",metavar="NUM",type="int",
                  help="pads season number to NUM places [default: %default]")

parser.add_option("--splitEpisodeChar",dest="splitEpisodeChar",metavar="CHAR",
                  help="Detects numbers split by CHAR as multi-episodic [default: %default]")

parser.add_option("--useUnixNaming",dest="useUnixNamingFlag",action="store_true",
                  help="replaces whitespace with '_' [default: %default]")

parser.add_option("--noUseUnixNaming",dest="useUnixNamingFlag",action="store_false",
                  help="no special handling for whitespace")

parser.add_option("-i","--allowPartialInfo",dest="allowPartialInfoFlag",action="store_true",
                  help="allow partially unknown information in new filename [default: %default]")

parser.add_option("-I","--noAllowPartialInfo",dest="allowPartialInfoFlag",action="store_false",
                  help="any unknown information will default the script to old filename")

parser.add_option("-r","--recursiveRename",dest="recursiveRenameFlag",action="store_true",
                  help="recursively rename files in all subdirectory [default: %default]")

parser.add_option("-R","--noRecursiveRename",dest="recursiveRenameFlag",action="store_false",
                  help="limit renaming to current directory")

parser.add_option("-d","--debug",dest="debugFlag",action="store_true",
                  help="print extra debug output [default: %default]")

parser.add_option("-D","--noDebug",dest="debugFlag",action="store_false",
                  help="do not print extra debug output")

parser.add_option("-v","--verbose",dest="verboseFlag",action="store_true",
                  help="print verbose output [default: %default]")

parser.add_option("-V","--noVerbose",dest="verboseFlag",action="store_false",
                  help="do not print verbose output")

parser.add_option("-q","--quiet",dest="quietFlag",action="store_true",
                  help="squelch all output [default: %default]")

parser.add_option("-Q","--noQuiet",dest="quietFlag",action="store_false",
                  help="print all output")

parser.add_option("-t","--topLevel",dest="topLevelDir",metavar="PATH",
                  help="top level rename hierarchy [default: current working directory]")

parser.add_option("--unattended",dest="unattendedFlag",action="store_true",
                  help="do not prompt for input [default: %default]")

parser.add_option("--interactive",dest="unattendedFlag",action="store_false",
                  help="require prompts for input")

parser.add_option("-o","--outputNameString",dest="outputNameString",metavar="STRING",
                  help="rename filename to formatted STRING [default: %default]")

parser.add_option("-O","--outputFullrunNameString",dest="outputFullrunNameString",metavar="STRING",
                  help="rename filename to formatted STRING if there is no season number specified [default: %default]")

parser.add_option("--showname",dest="manualShowname",
                  help="manually specify the showname to use [default: %default]")

parser.add_option("--season",dest="manualSeason",
                  help="manually specify the season to use [default: %default]")

parser.set_defaults(
                    undoBatchFlag=True,
                    nameBatchFlag=False,
                    writeCacheToFileFlag=True,
                    quashBatchEntriesFlag=False,
                    pretendFlag=True,
                    guessMultipartFlag=True,
                    handleFullRunFlag=True,
                    splitFullRunFlag=True,
                    guessMultipartFlag=True,
                    handleFullRunFlag=True,
                    splitFullRunFlag=True,
                    guessShowFromNameFlag=False,
                    assumeGroupedNumFlag=True,
                    groupNumSplit=2,
                    episodePadding=2,
                    seasonPadding=2,
                    splitEpisodeChar="-",
                    useUnixNamingFlag=False,
                    allowPartialInfoFlag=False,
                    recursiveRenameFlag=True,
                    debugFlag=False,
                    verboseFlag=True,
                    quietFlag=False,
                    topLevelDir=os.getcwd(),
                    unattendedFlag=True,
                    outputNameString=r"${showName} - S${seasonNum}E${episodeNum} - ${episodeTitle}",
                    outputFullrunNameString=r"${showName} - ${episodeNum} - ${episodeTitle}",
                    manualShowname=False,
                    manualSeason=False,
                    sourceListOrder=["epguidesTXT.source","tvComTXT.source","tvComCacheHTML.source","epguidesCacheHTML.source","epguidesWebHTML.source","tvComWebHTML.source"]
                    )

def setPrefsFromConfig(filename,parser):
    prefConfig=ConfigParser.RawConfigParser()
    prefConfig.read(filename)

    for section in prefConfig.sections():
        for option in prefConfig.options(section):
            if re.match(option,"undoBatchFlag",re.I):
                parser.set_defaults(undoBatchFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"nameBatchFlag",re.I):
                parser.set_defaults(nameBatchFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"writeCacheToFileFlag",re.I):
                parser.set_defaults(writeCacheToFileFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"quashBatchEntriesFlag",re.I):
                parser.set_defaults(quashBatchEntriesFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"pretendFlag",re.I):
                parser.set_defaults(pretendFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"guessMultipartFlag",re.I):
                parser.set_defaults(guessMultipartFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"handleFullRunFlag",re.I):
                parser.set_defaults(handleFullRunFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"splitFullRunFlag",re.I):
                parser.set_defaults(splitFullRunFlag=prefConfig.getboolean(section,option))                

            elif re.match(option,"guessShowFromNameFlag",re.I):
                parser.set_defaults(guessShowFromNameFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"assumedGroupedNumFlag",re.I):
                parser.set_defaults(assumedGroupedNumFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"useUnixNamingFlag",re.I):
                parser.set_defaults(useUnixNamingFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"allowPartialInfoFlag",re.I):
                parser.set_defaults(allowPartialInfoFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"recursiveRenameFlag",re.I):
                parser.set_defaults(recursiveRenameFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"debugFlag",re.I):
                parser.set_defaults(debugFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"verboseFlag",re.I):
                parser.set_defaults(verboseFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"quietFlag",re.I):
                parser.set_defaults(quietFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"unattendedFlag",re.I):
                parser.set_defaults(unattendedFlag=prefConfig.getboolean(section,option))

            elif re.match(option,"manualShowname",re.I):
                if re.search("^(?:True|False)",prefConfig.get(section,option),re.I):

                    parser.set_defaults(manualShowname=prefConfig.getboolean(section,option))
                else:
                    parser.set_defaults(manualShowname=prefConfig.get(section,option))

            elif re.match(option,"manualSeason",re.I):
                if re.search("^(?:True|False)",prefConfig.get(section,option),re.I):

                    parser.set_defaults(manualSeason=prefConfig.getboolean(section,option))
                else:
                    parser.set_defaults(manualSeason=prefConfig.get(section,option))

            elif re.match(option,"groupNumSplit",re.I):
                parser.set_defaults(groupNumSplit=prefConfig.getint(section,option))

            elif re.match(option,"episodePadding",re.I):
                parser.set_defaults(episodePadding=prefConfig.getint(section,option))

            elif re.match(option,"seasonPadding",re.I):
                parser.set_defaults(seasonPadding=prefConfig.getint(section,option))

            elif re.match(option,"splitEpisodeChar",re.I):
                parser.set_defaults(splitEpisodeChar=prefConfig.get(section,option))

            elif re.match(option,"outputNameString",re.I):
                parser.set_defaults(outputNameString=prefConfig.get(section,option))

            elif re.match(option,"outputFullrunNameString",re.I):
                parser.set_defaults(outputFullrunNameString=prefConfig.get(section,option))

    return parser


originalCwd=os.getcwd()
parser=setPrefsFromConfig(os.path.join(sys.path[0],r"Resources/preferences.cfg"),parser)
(opt,arg) = parser.parse_args()    
                     
def dPrnt(string,flag=opt.debugFlag,left="<dPrnt-:",right="->"):
    if flag and (opt.verboseFlag and not opt.quietFlag):
        print left+str(string)+right

def vPrnt(string,flag=opt.verboseFlag,left="{vPrnt-:",right="-}"):
    if flag and not opt.quietFlag:
        print left+str(string)+right

def qPrnt(string,flag=opt.quietFlag,left="",right=""):
    if not flag:
        print left+str(string)+right

def ePrnt(string,flag=True,left="!!!-",right="-!!!"):
    if not flag:
        print left+str(string)+right       

def checkRegexList(regexList,label="",pFlag=True):
    for x in range(len(regexList)):
        if regexList[x]:
            returnVal = regexList[x].group(0).strip()
            if pFlag:
                dPrnt("%sRE%i: %s" %(label,x+1,returnVal))
            return returnVal,x+1
    if pFlag:
        dPrnt("%s not parsed in string"%label)
    return "UNK","UNK"


def setSourceList():
    sourceList=[]

    if len(opt.sourceListOrder)>0:
        filenames=[]
        for source in opt.sourceListOrder:
            newSource=os.path.join(sys.path[0],"resources",source)
            if os.path.exists(newSource):
                filenames.append(newSource)
    else:
        filenames=glob.glob(os.path.join(sys.path[0],r"resources/*.source"))
                    
    for fileN in filenames:
        sourceList.append(getSourceFromConfig(fileN))

    return sourceList


def getSourceFromConfig(filename):
#returning 1 dictionary entry
    sourceConfig=ConfigParser.RawConfigParser()
    sourceConfig.read(filename)
    sourceDict={}

    dPrnt("getting source from %s"%filename)

    for section in sourceConfig.sections():
        dPrnt("section=%s"%(section))
        sourceDict[section.lower()]=True
        for option in sourceConfig.options(section):
            dPrnt("- source[\"%s_%s\"] = %s"%(section.lower(),option,sourceConfig.get(section,option)))
            if re.match("splash",option,re.IGNORECASE):
                sourceDict[section.lower()+"_splash"]=True
            elif re.match("search",option,re.IGNORECASE):
                sourceDict[section.lower()+"_search"]=True

            if re.search("flag$",option,re.IGNORECASE):
                regexFlag=0
                flags=sourceConfig.get(section,option)
                if re.search(r"re\.I",flags,re.I):
                    regexFlag=regexFlag+re.IGNORECASE
                if re.search(r"re\.M",flags,re.I):
                    regexFlag=regexFlag+re.MULTILINE
                if re.search(r"re\.D",flags,re.I):
                    regexFlag=regexFlag+re.DOTALL
                sourceDict["%s_%s"%(section.lower(),option)]=regexFlag
            elif re.search("swapterms$",option,re.IGNORECASE) and len(sourceConfig.get(section,option)):
                swapDict={}
                for swapTerm in sourceConfig.get(section,option).split(","):
                    swapDict[swapTerm.split("=")[0]]=swapTerm.split("=")[1]
                sourceDict["%s_%s"%(section.lower(),option)]=swapDict
                
            else:
                sourceDict["%s_%s"%(section.lower(),option)]=sourceConfig.get(section,option)

    return sourceDict
    
if opt.useUnixNamingFlag:
    whitespaceToUnderscore = string.maketrans(" ","_")

if opt.manualShowname or opt.manualSeason:
    qPrnt("manually specifying information, no recursion allowed")
    opt.recursiveRenameFlag = False

informationSources = setSourceList()

def renameFileList(inList):
    unRenamedLines = []
    source = []
    dest = []
    count = 0
    
    dPrnt("cwd: %s" % os.getcwd())
    parentDir=os.path.split(os.getcwd())[1].strip()
    parentOfParentDir=os.path.split(os.path.split(os.getcwd())[0])[1].strip()
    dPrnt("Parent of Parent Dir: %s" % parentOfParentDir)
    dPrnt("Parent Dir: %s" % parentDir)

    newNames = reshapeNames(inList,parentDir,parentOfParentDir)

    qPrnt("Attempting to make the following changes")
    qPrnt("----------------------------------------")
    for x in range(len(inList)):
        if newNames[x]!=inList[x]:
            qPrnt("%s %s %s" %(osRenameCommand,inList[x],newNames[x]))
            if not opt.pretendFlag:
                source.append(inList[x])
                dest.append(newNames[x])
            count = count + 1
        else:
            unRenamedLines.append("%s"%inList[x])
    if count == 0:
        qPrnt("no files changed")
        qPrnt("----------------------------------------")
        return None

    qPrnt("----------------------------------------")

    if opt.verboseFlag:
        vPrnt("renaming %i files"%count)

        
    if not opt.quietFlag and len(unRenamedLines):
        print "Unnamed files:|"
        print "--------------+"
        for untouchedFile in unRenamedLines:
           print "\t- %s" % untouchedFile

    prompt_confirm_change=""

    while not opt.unattendedFlag and not len(prompt_confirm_change)>0:
        prompt_confirm_change=raw_input("really make change? (y/n): ")

    if opt.unattendedFlag or re.match(prompt_confirm_change[0],"y",re.IGNORECASE):
        for i in range(len(source)):
            if os.path.exists(dest[i]):
                collisionFiles.append("%s -> %s"%(source[i],dest[i]))
                if not opt.unattendedFlag:
                    prompt=raw_input("overwrite %s? (y/n): "%dest[i])
                else:
                    prompt="n"

            if not os.path.exists(dest[i]) or re.match(prompt[0],"y",re.IGNORECASE):
                if not opt.pretendFlag:
                    try:
                        shutil.move(source[i],dest[i])
                    except:
                        ePrnt("error moving %s to %s"%(source[i],dest[i]))
                    
    if not opt.unattendedFlag and re.match(prompt_confirm_change[0],"y",re.IGNORECASE):
        if (opt.undoBatchFlag):
            makeNamingBatchFile(undoBatchName,osRenameCommand,dest,source)
        if (opt.nameBatchFlag):
            makeNamingBatchFile(nameBatchName,osRenameCommand,source,dest)


def makeNamingBatchFile(fileName,command,source,dest):
    vPrnt("creating batch file")
    if opt.quashBatchEntriesFlag:
        vPrnt("overwriting current batch")
    if len(source) != len(dest):
        qPrnt("mismatched rename lists batch create failed!")
    else:
        sourceNot=[]
        destNot=[]
        if os.path.exists(fileName):
            inF=open(fileName,"rb")

            if not opt.quashBatchEntriesFlag:
                modeString="ab"
                for line in inF.readlines():
                    if len(line)>1:
                        if line[0] != "#":
                            lineS=line.split()[1:]
                            if len(lineS)>1 and (lineS[1] in dest):
                                dPrnt(lineS[1]+"matched, dropped from file")
                                x=dest.index(lineS[1])
                                destNot.append(dest[x])
                                sourceNot.append(source[x])
                inF.close()
                
            else:
                modeString="wb"
        elif not opt.pretendFlag:
            modeString="wb"
            os.system("touch %s" %fileName)


        if not opt.pretendFlag:
            outF=open(fileName,modeString)

            if modeString=="wb":
                outF.write(batchHeaderString+"\n")            
        
        for x in range(len(source)):
            if not opt.pretendFlag:
                if source[x] not in sourceNot and dest[x] not in destNot:
                    if source[x]!=dest[x]:
                        outF.write("%s %s %s\n" %(command,source[x],dest[x]))
                    else:
                        dPrnt("batch source and dest match for %s, dropping line" % source[x])
        if not opt.pretendFlag:
            outF.close()
            

def reshapeNames(oldNameList,parentDir,parentOfParentDir,outputNameString=opt.outputNameString,fullrunNameString=opt.outputFullrunNameString):
    dPrnt("in reshapeNames")
    

    newNameList=[]

    for oldName in oldNameList:
        show,season,episode,title=searchInfo(oldName,parentDir,parentOfParentDir)
        extension=oldName[oldName.rfind("."):]
        if season=="FULL":
            nameTemplate=Template(fullrunNameString)
        else:
            nameTemplate=Template(outputNameString)
            
        if not opt.allowPartialInfoFlag:
            if show=="UNK" or season=="UNK" or episode=="UNK" or title=="UNK" or title=="":
                vPrnt("returning old name due to undefined information")
                unparsedFiles.append("%s/%s/%s"%(parentOfParentDir,parentDir,oldName))
                newName=oldName

            else:
                newName=nameTemplate.safe_substitute(showName=str(show),seasonNum=str(season),
                                            episodeNum=str(episode),
                                            episodeTitle=str(title))+extension
 
        else:
            if episode=="UNK" and (title=="UNK" or title==""):
                dPrnt("appending old name to prevent information loss")
                unparsedFiles.append("%s/%s/%s"%(parentOfParentDir,parentDir,oldName))
                newName=nameTemplate.safe_substitute(showName=str(show),seasonNum=str(season),
                                            episodeNum=str(episode),
                                            episodeTitle=str(title))+"-"+oldName
            else:
                newName=nameTemplate.safe_substitute(showName=str(show),seasonNum=str(season),
                                            episodeNum=str(episode),
                                            episodeTitle=str(title))+extension
                
        #deleting illegal filename characters
        newName=re.sub(r"[\!\?\$\&\*\^\"\:]","",newName)
        newName=re.sub(r"/"," ",newName)
        qPrnt(newName)
            
        if opt.useUnixNamingFlag:
            newName=newName.translate(whitespaceToUnderscore)
            
        newNameList.append(newName)
        
    return newNameList

def searchInfo(fileN,parentDir,parentOfParentDir):
    dPrnt("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    dPrnt("in searchInfo")
    vPrnt("+------------------------")
    vPrnt("| - fileN: %s" % fileN)
    vPrnt("+------------------------")
    
#- Getting tv show name from folder
    
    parentDir=os.path.split(os.getcwd())[1].strip()
    parentOfParentDir=os.path.split(os.path.split(os.getcwd())[0])[1].strip()

    dPrnt("%s -> "%parentDir)
    parentDir=re.sub(r"[^A-Za-z0-9]"," ",parentDir)
    #replace non alpha-numerics with whitespace
    dPrnt("-> %s "%parentDir)

    shownameIndex=0

    if not opt.manualShowname:
        shownameRegexList = []
        #shownameRE1
        shownameRegexList.append(re.search(r".*(?=(Season|Series))",parentDir,re.IGNORECASE))
        #shownameRE2
        shownameRegexList.append(re.search(r".*?(?=s\d+)",parentDir,re.IGNORECASE))
        #shownameRE3
        shownameRegexList.append(re.search(r"(\w|\S)*?(?=(\d))",parentDir,re.IGNORECASE))
        #shownameRE4
        shownameRegexList.append(re.search(r".*",parentDir,re.IGNORECASE))

        showname,correctRE = checkRegexList(shownameRegexList,"showname")

        if len(showname)==0:
            dPrnt("using parent of parent directory as show name")
            showname=parentOfParentDir
    else:
        showname = opt.manualShowname

    if opt.guessShowFromNameFlag:
        shownameFileRE1,correctRE=checkRegexList([re.search(r"[A-Z]+(?=[\ _\.])",fileN,re.IGNORECASE)],"shownameFile1")
        shownameFileRE2,correctRE=checkRegexList([re.search(r"(?<=[\. _]).+?(?=[A-Z\ \._][0-9])",fileN,re.IGNORECASE)],"shownameFile2")

        shownameWordList=showname.split()

        dPrnt("| checking showname in filename")
        dPrnt("+ fileN: %s" % fileN)
        dPrnt("+ showN: %s" % showname)
        dPrnt("shownameFileRE1: %s" % shownameFileRE1)
        dPrnt("shownameFileRE2: %s" % shownameFileRE2)
        dPrnt("---")
        dPrnt(str(shownameWordList))
        dPrnt("---")

        maxShownameIndex=0
        wordLength=0
        foundWord=None

        for shownameWord in range(len(shownameWordList[:-1])):
            shownameIndex=fileN.find(shownameWordList[shownameWord])
            if shownameIndex==-1:
                shownameIndex=0
            if shownameIndex>maxShownameIndex:
                wordLength=len(shownameWordList[shownameWord])
                maxShownameIndex=shownameIndex
                foundWord=shownameWordList[shownameWord]

        maxShownameIndex=maxShownameIndex+wordLength

        dPrnt("Found %s in %s"%(foundWord,fileN))
        dPrnt("Leaving: %s"%fileN[maxShownameIndex:])

        shownameIndex=maxShownameIndex
    else:
        shownameIndex=0
        
#- Getting season number from filename
    seasonRet="UNK"
    episodeRet="UNK"

    if not opt.manualSeason:
        seasonRegexList=[]

        #seasonRE1
        seasonRegexList.append(re.search(r"^[0-9]+",fileN[shownameIndex:],re.I))
        #seasonRE2
        seasonRegexList.append(re.search(r"(?<=(Season)[\ \._])[0-9]*",fileN[shownameIndex:],re.I))
        #seasonRE3
        seasonRegexList.append(re.search(r"(?<=[\ _xs\.])[0-9]+",fileN[shownameIndex:],re.I))
        #seasonRE4
        seasonRegexList.append(re.search(r"(?<=[\ _xs\.])[0-9]+",parentDir,re.I))
        
        seasonRet,correctRE=checkRegexList(seasonRegexList,"season")

        if seasonRet!="UNK":
            seasonIndex=fileN.find(seasonRet)+len(seasonRet)
        else:
            seasonIndex=0

        if correctRE==4:
            seasonIndex=0
                      
        if seasonRet != "UNK" and opt.assumeGroupedNumFlag:
            dPrnt("trying to split episode")
            if len(seasonRet)>opt.groupNumSplit:
                episodeRet=seasonRet[-opt.groupNumSplit:]
                seasonRet=seasonRet[:-opt.groupNumSplit]
                dPrnt("splitting value into s:%s and leaving:%s "%(seasonRet,fileN[seasonIndex:]))
            else:
                dPrnt("---")
                dPrnt("index set at: %d, leaving: %s "%(seasonIndex,fileN[seasonIndex:]))
                dPrnt("---")
    else:
        if opt.manualSeason=="Full":
            seasonRet="UNK"
        else:
            seasonRet=opt.manualSeason
        seasonIndex=shownameIndex
                
            
#- Getting episode number from filename

    if episodeRet == "UNK":
        episodeRegexList = []

        episodeRegexList.append(re.search(r"(?<=e])[0-9]+",fileN,re.I))
        episodeRegexList.append(re.search(r"(?<=[\ _xe\.])[0-9]+",fileN[seasonIndex:],re.I))
        episodeRegexList.append(re.search(r"[0-9]+",fileN[seasonIndex:],re.I))
        
        episodeRet,correctRE=checkRegexList(episodeRegexList,"episode")

        dPrnt(re.findall(r"(?<=\D)[0-9]+(?=\D)",fileN[seasonIndex:]))


    if episodeRet!="UNK" and opt.guessMultipartFlag and len(re.findall(r"(?<=\D)[0-9]+(?=\D)",fileN[seasonIndex:]))>0:
        dPrnt("check for multipart episode read as show number")
        dPrnt("originally thought episodeRet was: %s"%episodeRet)
        multipartCheckList=[r"(part|p|pt)[\.]?[ ]*[0]*%s"%str(int(episodeRet[:opt.episodePadding])),
                                r"[{\[\(].*%s.*[}\]\)]"%str(int(episodeRet[:opt.episodePadding]))]

        for checkRegex in multipartCheckList:
            if re.search(checkRegex,fileN,re.IGNORECASE):
                dPrnt("found %s in filename, assuming multipart episode"%re.search(checkRegex,fileN,re.IGNORECASE).group(0))
                episodeRet="UNK"
                
    if episodeRet == "UNK" and seasonRet != "UNK" and re.search(r"[0-9]+",fileN,re.I):
        dPrnt("assuming only number in filename is episode")

        dPrnt("using folder name to find season number")
        episodeRet=seasonRet

        seasonRegexList = []
        seasonRegexList.append(re.search(r"(?<=[\ _xs\.])[0-9]+",parentDir,re.I))

        seasonRet,correctRE=checkRegexList(seasonRegexList,"seasonRedo")

        if seasonRet=="UNK":
            dPrnt("No season parsed, assuming full run")
            seasonRet="FULL"

    if episodeRet!="UNK":
        dPrnt("checking for double episodes")

        episodeDoubleList = []
        episodeDoubleList.append(re.search(r"%s%s[0-9]+"%(episodeRet,opt.splitEpisodeChar),fileN,re.I))

        episodeDouble,correctRE=checkRegexList(episodeDoubleList,"episodeDouble")

        if episodeDouble != "UNK":
            dPrnt("found double episode number: %s"%episodeDouble)
            episodeRet=episodeDouble
        else:
            dPrnt("detecting single episode only")

#- Getting the episde title from a source
    episodeHolder=""
    titleHolder=""

    if seasonRet.isdigit():
        seasonRet=str(int(seasonRet))
    
    if episodeRet!="UNK" and showname != "UNK":
        for episodeSplit in episodeRet.split(opt.splitEpisodeChar):
            for source in informationSources:     
                #this handles double episode numbers
                if episodeSplit.isdigit():
                    dPrnt("checking split episode %s"%episodeSplit)
                    titlePiece,seasonRet,episodePiece=getTitleFromSource(source,showname,seasonRet,str(int(episodeSplit)))
                    dPrnt("returned titlePiece: %s and episodePiece %s"%(titlePiece,episodePiece))
                else:
                    ePrnt("non-numerical episode num")
                    titlePiece="UNK"

                if titlePiece!="UNK":
                    if episodePiece.isdigit():
                        episodePiece=episodePiece.zfill(opt.episodePadding)
                    episodeHolder=episodeHolder+opt.splitEpisodeChar+episodePiece
                    titleHolder=titleHolder+(" %s ")%opt.splitEpisodeChar+titlePiece
                    break

    else:
        title="UNK"

    if seasonRet.isdigit():
        seasonRet=seasonRet.zfill(opt.seasonPadding)

    episodeRet=episodeHolder[len(opt.splitEpisodeChar):]
    title=titleHolder[len(opt.splitEpisodeChar)+2:]
        
    vPrnt("+------------------------")
    vPrnt("| - [showname]: %s [seasonRet]: %s [episodeRet]: %s [title]: %s" %(showname,seasonRet,episodeRet,title))
    vPrnt("+------------------------")

    return showname,seasonRet,episodeRet,title
        
def getTitleFromSource(source,showname,season,episode):
    dPrnt("Using [showname]: %s [season]: %s [episode]: %s" %(showname,season,episode))
        
    if source.has_key("spec_name"):
        dPrnt("using source name: %s"%source["spec_name"])

    newEpisode=str(episode)
    newSeason=str(season)

    if source.has_key("site"):
        dPrnt("is site: %s "%source["site_address"])
        stringToPrint=source["spec_name"]

#--- splash page searches out the right URL, and fills out pullURL
        if source.has_key("site_splash"):
            dPrnt("--------------filling out the splash template--------------")            
            if source.has_key("site_splashtemplate"):
                dPrnt("site_splashtemplate=%s"%source["site_splashtemplate"])
                splashTerm=Template(source["site_splashtemplate"]).safe_substitute(shownameT=showname)
                dPrnt("splashTerm=%s"%splashTerm)
            else:
                splashTerm=showname

            if source.has_key("site_splashtemplate_swapterms"):
                dPrnt("swapping out splash terms")
                for key in source["site_splashtemplate_swapterms"].keys():
                    dPrnt("re.sub [%s] -> [%s]"%(key,source["site_splashtemplate_swapterms"][key]),left="",right="")
                    searchTerm=re.sub(key,source["site_splashtemplate_swapterms"][key],splashTerm)
                    dPrnt("leaving=%s"%searchTerm)
                
            pullURL=r"%s%s"%(source["site_address"],searchTerm)    
            dPrnt(r"splashpageURL:%s"%pullURL)

            if source.has_key(pullURL):
                if source[pullURL]:
                    dPrnt("loading cached results")
                    splashPage=source[pullURL]
                else:
                    dPrnt("cached results show unknown information")
                    return "UNK",season,episode
            else:
                try:
                    splashPage=urllib2.urlopen(pullURL).read()
                    dPrnt("caching the contents of %s"%pullURL)
                    source[pullURL]=splashPage
                except:
                    dPrnt("splashpage not found, caching failed, returning unknown")
                    source[pullURL]=False
                    return "UNK",season,episode

            if source.has_key("site_splashlineregex"):
                if source.has_key("site_splashlineregex_swapterms"):
                    dPrnt("swapping out splashpage regex terms")
                    searchTerm=showname
                    
                    for key in source["site_splashlineregex_swapterms"].keys():
                        dPrnt("re.sub [%s] -> [%s]"%(key,source["site_splashlineregex_swapterms"][key]),left="",right="")
                        searchTerm=re.sub(key,source["site_splashlineregex_swapterms"][key],searchTerm)
                        dPrnt("leaving=%s"%searchTerm)

                    lineRegex=Template(source["site_splashlineregex"]).safe_substitute(shownameT=searchTerm)
                        
                    if source.has_key("site_splashlineregexflag"):
                        lineRegex=[re.search(lineRegex,splashPage,source["site_splashlineregexflag"])]
                    else:
                        lineRegex=[re.search(lineRegex,splashPage)]
                        
                    pullURL,correctRE=checkRegexList(lineRegex,pFlag=True)

                    if source.has_key("site_splashlineprefixtemplate"):
                        if episode.isdigit() and season.isdigit():
                            pullURL=pullURL+Template(source["site_splashlineprefixtemplate"]).safe_substitute(episodeT=episode,seasonT=season)
                        else:
                            pullURL=pullURL+Template(source["site_splashlineprefixtemplate"]).safe_substitute(episodeT="",seasonT="")
            
        

                    dPrnt("final url=%s"%pullURL)
                    
                    if source.has_key(pullURL):
                        if source[pullURL]:
                            dPrnt("loading cached results")
                            dump=source[pullURL]
                        else:
                            dPrnt("cached results of site page show unknown information")
                            return "UNK",season,episode
                    else:
                        try:
                            dump=urllib2.urlopen(pullURL).read()
                            dPrnt("caching the contents of %s"%pullURL)
                            source[pullURL]=dump


                            if opt.writeCacheToFileFlag and source.has_key("site_cachefilename"):
                                vPrnt("writing cache to filename: %s"%source["site_cachefilename"])
                                try:
                                    if not opt.pretendFlag:
                                        outF=open(source["site_cachefilename"],"wb")
                                        outF.write(dump)
                                        outF.close()
                                except:
                                    ePrnt("error writing cache to %s"%source["site_cachefilename"])


                        except:
                            dPrnt("site page not found, caching failed, returning unknown")
                            source[pullURL]=False
                            return "UNK",season,episode

        if source.has_key("site_search"):
            dPrnt("--------------filling out the search template--------------")
            
            if source.has_key("site_searchtemplate"):
                dPrnt("site_searchtemplate=%s"%source["site_searchtemplate"])
                searchTerm=Template(source["site_searchtemplate"]).safe_substitute(shownameT=showname)
                dPrnt("searchTerm=%s"%searchTerm)

            else:
                searchTerm=showname

            if source.has_key("site_searchtemplate_swapterms"):
                dPrnt("swapping out search terms")
                for key in source["site_searchtemplate_swapterms"].keys():
                    dPrnt("re.sub [%s] -> [%s]"%(key,source["site_searchtemplate_swapterms"][key]),left="",right="")
                    searchTerm=re.sub(key,source["site_searchtemplate_swapterms"][key],searchTerm)
                    dPrnt("leaving=%s"%searchTerm)
    
                
            pullURL=r"%s%s"%(source["site_address"],searchTerm)    
            dPrnt(r"searchURL:%s"%pullURL)

            if source.has_key(pullURL):
                if source[pullURL]:
                    dPrnt("loading cached results")
                    dump=source[pullURL]
                else:
                    dPrnt("cached results of site page show unknown information")
                    return "UNK",season,episode
            else:
                try:
                    
                    dump=urllib2.urlopen(pullURL).read()
                    dPrnt("caching the site contents of %s"%pullURL)
                    source[pullURL]=dump

                    if opt.writeCacheToFileFlag and source.has_key("site_cachefilename"):
                        vPrnt("writing cache to filename: %s"%source["site_cachefilename"])
                        try:
                            if not opt.pretendFlag:
                                outF=open(source["site_cachefilename"],"wb")
                                outF.write(dump)
                                outF.close()
                        except:
                            ePrnt("error writing cache to %s"%source["site_cachefilename"])

                except:
                    dPrnt("site page not found, caching failed, returning unknown")
                    source[pullURL]=False
                    return "UNK",season,episode
        
    elif source.has_key("file"):
        dPrnt("is file: %s"%source["file_filename"])
        stringToPrint=source["file_filename"]
        if os.path.exists(source["file_filename"]):
            dump=open(source["file_filename"],"rb").read()
        else:
            dPrnt("%s does not exist"%source["file_filename"])
            return "UNK",season,episode


    else:
        dPrnt("incorrectly specified source type. add [FILE] or [SITE] to your source file")
        return "UNK",season,episode


    #dump exists and holds the text to be parsed

    dPrnt("searching for %s in %s"%(showname,stringToPrint))

    if (season == "UNK" or season == "FULL") and episode !="UNK":
        if source.has_key("broadcast_ordering"):
            if source.has_key("broadcast_ordering_bodyregex"):
                dPrnt("using body regex: %s"%source["broadcast_ordering_bodyregex"])
                bodyRegex=Template(source["broadcast_ordering_bodyregex"])
                bodyRegex=bodyRegex.safe_substitute(episodeT=episode,seasonT=season)
                dPrnt("substituted: %s"%bodyRegex)

                if source.has_key("broadcast_ordering_titleregexflag"):
                    bodyRegex=[re.search(source["broadcast_ordering_bodyregex"],dump,source["broadcast_ordering_bodyregexflag"])]
                else:
                    bodyRegex=[re.search(source["broadcast_ordering_bodyregex"],dump)]

                

                dump,correctRE=checkRegexList(bodyRegex,pFlag=False)

                

            if source.has_key("broadcast_ordering_linefindallregex"):
                dPrnt("using findall regex: %s"%source["broadcast_ordering_linefindallregex"])
                lineTemplatePattern=Template(source["broadcast_ordering_linefindallregex"])
                lineTemplatePattern=lineTemplatePattern.safe_substitute(episodeT=episode,seasonT=season)
                dPrnt("substituted: %s"%lineTemplatePattern)

                if source.has_key("broadcast_ordering_linefindallregexflag"):
                    lineList=re.findall(lineTemplatePattern,dump,source["broadcast_ordering_linefindallregexflag"])
                else:
                    lineList=re.findall(lineTemplatePattern,dump)

                if int(episode) > len(lineList):
                    dPrnt("%s > %s"%(episode,str(len(lineList))))
                    return "UNK",season,episode
                else:
                    #dump is now the correct instance
                    dPrnt("using lineList[%s] of max %s"%(episode,str(len(lineList))))
                    dump=lineList[int(episode)-1]


            elif source.has_key("broadcast_ordering_lineregex"):
                dPrnt("using line regex: %s"%source["broadcast_ordering_lineregex"])
                lineTemplatePattern=Template(source["broadcast_ordering_lineregex"])
                lineTemplatePattern=lineTemplatePattern.safe_substitute(episodeT=episode,seasonT=season)
                dPrnt("substituted: %s"%lineTemplatePattern)
                if source.has_key("broadcast_ordering_lineregexflag"):
                    lineRegex=[re.search(lineTemplatePattern,dump,source["broadcast_ordering_lineregexflag"])]
                else:
                    lineRegex=[re.search(lineTemplatePattern,dump)]
                    
                #dump now has a manageable chunk
                dump,correctRE=checkRegexList(lineRegex,pFlag=False)


            if source.has_key("broadcast_ordering_splitseasonregex") and source.has_key("broadcast_ordering_splitepisoderegex"):
                if source.has_key("broadcast_ordering_splitseasonregex_flag"):
                    seasonRegex=[re.search(source["broadcast_ordering_splitseasonregex"],dump,source["broadcast_ordering_splitseasonregexflag"])]
                else:
                    seasonRegex=[re.search(source["broadcast_ordering_splitseasonregex"],dump)]
                if source.has_key("broadcast_ordering_splitepisoderegex_flag"):
                    episodeRegex=[re.search(source["broadcast_ordering_splitepisoderegex"],dump,source["broadcast_ordering_splitepisoderegexflag"])]
                else:
                    episodeRegex=[re.search(source["broadcast_ordering_splitepisoderegex"],dump)]

                newSeason,correctRE=checkRegexList(seasonRegex,"seasonRegex")
                if newSeason=="UNK":
                    newSeason=season
                newEpisode,correctRE=checkRegexList(episodeRegex,"episodeRegex")
                if newEpisode=="UNK":
                    newEpisode=episode
                        
            if source.has_key("broadcast_ordering_titleregex"):
                dPrnt("using title regex: %s"%source["broadcast_ordering_titleregex"])
                if source.has_key("broadcast_ordering_titleregexflag"):
                    titleRegex=[re.search(source["broadcast_ordering_titleregex"],dump,source["broadcast_ordering_titleregexflag"])]
                else:
                    titleRegex=[re.search(source["broadcast_ordering_titleregex"],dump)]
                    
                title,correctRE=checkRegexList(titleRegex,pFlag=False)
                dPrnt("title: %s"%title)

                return title.strip(),newSeason,newEpisode

            
            
        else:
            try:
                dPrnt("invalid broadcast order run source %s"%source["spec_name"])
            except:
                dPrnt("invalid broadcast order run source")
            return "UNK",season,episode

            
    elif source.has_key("season_ordering"):
        dPrnt("attempting to use season/episode order")

        if source.has_key("season_ordering_linefindallregex"):
            dPrnt("using findall regex: %s"%source["season_ordering_linefindallregex"])
            lineTemplatePattern=Template(source["season_ordering_linefindallregex"])
            lineTemplatePattern=lineTemplatePattern.safe_substitute(episodeT=episode,seasonT=season)
            dPrnt("substituted: %s"%lineTemplatePattern)

            if source.has_key("season_ordering_linefindallregexflag"):
                lineList=re.findall(lineTemplatePattern,dump,source["season_ordering_linefindallregexflag"])
            else:
                lineList=re.findall(lineTemplatePattern,dump)

            if int(episode) > len(lineList):
                dPrnt("%s > %s"%(episode,str(len(lineList))))
                return "UNK",season,episode
            else:
                #dump is now the correct instance
                dPrnt("using lineList[%s] of max %s"%(episode,str(len(lineList))))
                dump=lineList[int(episode)-1]


        elif source.has_key("season_ordering_lineregex"):
            dPrnt("using line regex: %s"%source["season_ordering_lineregex"])
            lineTemplatePattern=Template(source["season_ordering_lineregex"])
            lineTemplatePattern=lineTemplatePattern.safe_substitute(episodeT=episode,seasonT=season)
            dPrnt("substituted: %s"%lineTemplatePattern)
            if source.has_key("season_ordering_lineregexflag"):
                lineRegex=[re.search(lineTemplatePattern,dump,source["season_ordering_lineregexflag"])]
            else:
                lineRegex=[re.search(lineTemplatePattern,dump)]
                
            #dump now has a manageable chunk
            dump,correctRE=checkRegexList(lineRegex,pFlag=False)

            
        if source.has_key("season_ordering_titleregex"):
            dPrnt("using title regex: %s"%source["season_ordering_titleregex"])
            if source.has_key("season_ordering_titleregexflag"):
                titleRegex=[re.search(source["season_ordering_titleregex"],dump,source["season_ordering_titleregexflag"])]
            else:
                titleRegex=[re.search(source["season_ordering_titleregex"],dump)]
                
            title,correctRE=checkRegexList(titleRegex,pFlag=False)
            dPrnt("title: %s"%title)

            return title.strip(),season,episode
            
    else:
        dPrnt("unable to use season ordering, returning unknown")
        return "UNK",season,episode
        
    

def main():
    startTime=time.time()
    
    fileTypes = re.compile(r'.*(\.avi|mkv|\.mpg|\.rm|\.flv)$',re.IGNORECASE)

    os.chdir(opt.topLevelDir)
    
    for root,dirs,fileNameList in os.walk(opt.topLevelDir):
        qPrnt("checking %s" %root)
        os.chdir(root)
        
        if len(fileNameList)>0:
            newFileNameList = []

            for fileN in fileNameList:
                if fileTypes.match(fileN):
                    newFileNameList.append(fileN)

            listLength=len(newFileNameList)

            vPrnt("Attempting to rename %s files" % listLength)

            if listLength>0:
                renameFileList(newFileNameList)

                if not opt.unattendedFlag:

                    prompt=""
                    while not len(prompt)>0:
                        prompt=raw_input("continue? (y/n): ")
                    
                    if not re.match(prompt[0],"y",re.IGNORECASE):
                        break            
            else:
                vPrnt("no usable files found in %s" % root)

            qPrnt(time.time()-startTime)
            qPrnt("---")

        if not opt.recursiveRenameFlag:
            break
        
main()
os.chdir(originalCwd)

if not opt.quietFlag:
    qPrnt("--------------------")
    qPrnt("unParsedFiles")
    for x in unparsedFiles:
        print x
    qPrnt("--------------------")
    qPrnt("unfoundWebsites")
    for x in unfoundWebsites:
        print x
    qPrnt("--------------------")
    qPrnt("collidedFiles")
    for x in collisionFiles:
        print x
    qPrnt("--------------------")
